import os
from curl_cffi import requests
import re
from util.logger import get_logger
from util.useragent import get_headers_init_user_agent
import shutil
logger = get_logger("彼岸图网.log", __name__)
try:
    root = 'static/彼岸图网'
    if os.path.exists(root):
        shutil.rmtree(root)
    os.makedirs(root)
    logger.info("程序启动")
    num = 5
    url = f'https://pic.netbian.com/index_{num}.html'
    headers = {
        'User-agent': get_headers_init_user_agent()
    }
    response = requests.get(url, headers=headers, impersonate="chrome100")
    response_text = response.content.decode('gbk')
    thumbnail_items = re.findall(r'<li><a href="(.*?)" target="_blank"><img src="(.*?)" alt="(.*?)" /><b>.*?</b></a></li>', response_text)
    logger.debug("开始爬取网站图片")
    for item in thumbnail_items:
        detail_url = f'https://pic.netbian.com{item[0]}'
        thumbnail_url = f'https://pic.netbian.com{item[1]}'
        title = item[2]
        # 保存缩略图
        logger.debug(f"开始保存 {title} 的缩略图")
        headers.update({
            'Referer': url
        })
        thumbnail_response = requests.get(thumbnail_url, headers=headers)
        with open(f"{root}/{title}_thumbnail.jpg", "wb") as f:
            f.write(thumbnail_response.content)
        logger.debug(f"保存 {title}_thumbnail.jpg 成功")
        # 获取详情图
        logger.debug(f"开始获取 {title} 的详情图")
        detail_response = requests.get(detail_url, headers=headers)
        detail_text = detail_response.content.decode('gbk')
        preview_url = re.search(r'<div class="photo-pic"><a href="" id="img"><img src="(.*?)" data-pic=".*?" alt=".*?" title=".*?"></a></div>', detail_text)
        preview_url = f"https://pic.netbian.com{preview_url.group(1)}"
        logger.debug(f"获取 {title}详情图 成功")
        # 保存详情图
        logger.debug(f"开始保存 {title} 的详情图")
        headers.update({
            'Referer': detail_url
        })
        preview_response = requests.get(preview_url, headers=headers)
        with open(f"{root}/{title}_preview.jpg", "wb") as f:
            f.write(preview_response.content)
        logger.debug(f"保存 {title}_preview.jpg 成功")
        break
except Exception as e:
    logger.error(e)

logger.info("程序运行完毕")